//
//  SearchViewController.m
//  TestByFF
//
//  Created by hanxifeng on 16/6/30.
//  Copyright © 2016年 haixu. All rights reserved.
//  搜索地址页

#import "SearchViewController.h"
#import "FSearchBar.h"
#import "FSearchModel.h"

@interface SearchViewController ()<UITableViewDelegate,UITableViewDataSource,FSearchBarDelegate>
@property (nonatomic,strong)FSearchBar *fSearchBar;
@end

@implementation SearchViewController{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    NSMutableArray *_resultArray;
    NSMutableArray *_pinYinArray;//汉字转成拼音的数组
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    //search bar
    [self buildSearchBar];
    //tableview
    [self buildTableView];
    //刷新控件
    [self setupRefresh];
}
#pragma mark - buildui
-(void)buildSearchBar{
    
    FSearchBar *fSearchBar = [[FSearchBar alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 44)];
    fSearchBar.delegate = self;
    self.fSearchBar = fSearchBar;
}
-(void)buildTableView{
    _dataArray = [[NSMutableArray alloc] init];
    _resultArray = [[NSMutableArray alloc] init];
    _pinYinArray = [[NSMutableArray alloc] init];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    _tableView.delegate = self;
    _tableView.dataSource= self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.rowHeight = 35;
    _tableView.tableHeaderView = self.fSearchBar;
    [self.view addSubview:_tableView];
}
#pragma mark - request
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    _tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    //触发刷新方法
    [_tableView.mj_header beginRefreshing];
}

// 开始进入刷新状态
- (void)headerRereshing
{
    //加载数据
    [self httpRequestList];
    //取消搜索
    [self.fSearchBar showCancleBtn:NO withText:NO];
}

-(void)httpRequestList{
    NSString *urlStr = @"http://wngs.test.xuhaisoft.com/upgradeapi/shequ_list.php";
    NSDictionary *paramsDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"4001",@"cityCode",@"-1",@"count", nil];
    [HTTPRequestTool POST:urlStr params:paramsDic success:^(id JSON,NSString *responseString) {
        [_tableView.mj_header endRefreshing];
        if (JSON!=nil&&[[JSON objectForKey:@"recode"] isEqualToString:@"0"]) {
            [_dataArray removeAllObjects];
            NSArray *shequList = [JSON objectForKey:@"list"];
            //封装对象 数据处理
            [self handleData:shequList];
        }else{
            JSON==nil?[SVProgressHUD showErrorWithStatus:@"数据解析失败"]:[SVProgressHUD showErrorWithStatus:[JSON objectForKey:@"msg"]];
        }
    } failure:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        error.code == NSURLErrorTimedOut?[SVProgressHUD showErrorWithStatus:@"网络请求超时"]:[SVProgressHUD showErrorWithStatus:@"网络请求失败"];
        NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [error userInfo]);
    }];
}

#pragma mark - delegate
#pragma mark tableview delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _resultArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //创建cell
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    //传递模型
    FSearchModel *model = _resultArray[indexPath.row];
    cell.textLabel.text = model.shequName;
    
    return cell;
}
#pragma mark scrollview delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
}
#pragma mark FSearchBar delegate
//文本框获取焦点 开始搜索
-(void)FSearchBarDidBeginEditing:(FSearchBar *)searchBar{
    
}
//文字有改动触发
-(void)FSearchBarDidChangeEditing:(FSearchBar *)searchBar withTextString:(NSString *)textString{
    if (textString.length==0) {//搜索框上无字
        [self refreshTableViewWithResulteArray:_dataArray];
        return;
    }
    if ([self isLettersWithString:textString]) {
        //进来说明是英文 转成小写
        textString = [textString lowercaseString];
        
        //看输入的字母是否被包含在拼音首字母数组中
         NSPredicate *filterPredicateFirstPinYin = [NSPredicate predicateWithFormat:@"shequNameFirstPinYin CONTAINS %@",textString];
        //看输入的字母是否被包含在拼音全拼数组中
        NSPredicate *filterPredicatePinYin = [NSPredicate predicateWithFormat:@"shequNamePinYin CONTAINS %@",textString];
        NSArray *filterArray = [_pinYinArray filteredArrayUsingPredicate:filterPredicateFirstPinYin];
        //如果首字母没匹配到再匹配全拼
        if (filterArray.count==0) filterArray = [_pinYinArray filteredArrayUsingPredicate:filterPredicatePinYin];
        [self refreshTableViewWithResulteArray:filterArray];
    }else{
        //不是英文的其他字符 汉字  数组  特殊符号等
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"shequName CONTAINS %@",textString];
        NSArray *filterArray = [_dataArray filteredArrayUsingPredicate:filterPredicate];
        [self refreshTableViewWithResulteArray:filterArray];
    }
}
//取消搜索
-(void)FSearchBarCancleEditing:(FSearchBar *)searchBar{
    [self refreshTableViewWithResulteArray:_dataArray];
}
//键盘搜索按钮
-(void)FSearchBarSearchBtnClick:(FSearchBar *)searchBar{

}
#pragma mark - action
#pragma mark click action

#pragma mark local action
//是否是字母
-(BOOL)isLettersWithString:(NSString *)string{
    NSString *regularLetters = @"^[A-Za-z]+$";
    NSPredicate *lettersPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularLetters];
    return [lettersPre evaluateWithObject:string];
}
//把汉字转成字母 返回数组中0索引是汉字全拼 1索引是汉字首字母拼
-(NSArray *)convertLettersFromCharacter:(NSString *)character{
    //可变字符串
    NSMutableString *charMutableStr = [NSMutableString stringWithString:character];
    //带声调的拼音
    CFStringTransform((CFMutableStringRef)charMutableStr, NULL, kCFStringTransformMandarinLatin, NO);
    //不带声调的拼音
    CFStringTransform((CFMutableStringRef)charMutableStr, NULL,kCFStringTransformStripDiacritics, NO);
    /*多音字处理*/
    if ([[character substringToIndex:1] compare:@"长"] == NSOrderedSame)
    {
        [charMutableStr replaceCharactersInRange:NSMakeRange(0, 5) withString:@"chang"];
    }
    else if ([[character substringToIndex:1] compare:@"沈"] == NSOrderedSame)
    {
        [charMutableStr replaceCharactersInRange:NSMakeRange(0, 4) withString:@"shen"];
    }
    else if ([[character substringToIndex:1] compare:@"厦"] == NSOrderedSame)
    {
        [charMutableStr replaceCharactersInRange:NSMakeRange(0, 3) withString:@"xia"];
    }
    else if ([[character substringToIndex:1] compare:@"地"] == NSOrderedSame)
    {
        [charMutableStr replaceCharactersInRange:NSMakeRange(0, 3) withString:@"di"];
    }
    else if ([[character substringToIndex:1] compare:@"重"] == NSOrderedSame)
    {
        [charMutableStr replaceCharactersInRange:NSMakeRange(0, 5) withString:@"chong"];
    }
    //转成小写
    NSString *returnStr = [charMutableStr lowercaseString];    //去空格后的汉字全拼
    NSString *removeSpaceReturnStr = [returnStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    //根据空格把字符串转成数组
    NSArray *splitArray = [returnStr componentsSeparatedByString:@" "];
    //截取首字母拼串
    __block NSString *firstLetters = @"";
    [splitArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *firstLetter = obj.length>0?[obj substringToIndex:1]:@"";
        firstLetters = [NSString stringWithFormat:@"%@%@",firstLetters,firstLetter];
    }];
    //去空格返回
    return [NSArray arrayWithObjects:removeSpaceReturnStr,firstLetters, nil];
}
-(void)handleData:(NSArray *)shequList{
    for (int i=0; i<shequList.count; i++) {
        FSearchModel *model = [[FSearchModel alloc] init];
        model.shequId = [shequList[i] objectForKey:@"sqid"];
        model.shequName = [shequList[i] objectForKey:@"shequ"];
        model.detailAddress = [shequList[i] objectForKey:@"addr"];
        [_dataArray addObject:model];
    }
    //每次请求都要清空原来数组中的数据 否则有冗余
    [_pinYinArray removeAllObjects];
    //1 数组中的元素  2 当前遍历到的索引  3是否停止循环 *stop=YES 即可跳出循环
    [_dataArray enumerateObjectsUsingBlock:^(FSearchModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //将社区的汉字转成拼音
        NSArray *tempArray = [self convertLettersFromCharacter:obj.shequName];
        //社区的拼音转换赋值给对象
        obj.shequNamePinYin = tempArray[0];
        obj.shequNameFirstPinYin = tempArray[1];
        [_pinYinArray addObject:obj];
    }];
    [self refreshTableViewWithResulteArray:_dataArray];
}
//刷新tableview
-(void)refreshTableViewWithResulteArray:(NSArray *)resulteArrray{
    [_resultArray removeAllObjects];
    [_resultArray addObjectsFromArray:resulteArrray];
    [_tableView reloadData];
}
@end
